import compose from 'koa-compose';
import uuid from 'node-uuid';

async function logger(ctx, next) {
    ctx.request.reqId = uuid();

    const referer = (ctx.get('referer') || ctx.get('referrer') || '').slice(0, 768);
    const userAgent = (ctx.get('user-agent') || '').slice(0, 384);

    global.logger.info('%s %s - %s', ctx.method, ctx.url, ctx.request.body);

    await next();

    if (ctx.method !== 'HEAD') {
        global.logger.info(
            '%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s',
            `IP: ${ctx.ip}`,
            `Href: ${ctx.request.href || 'null'}`,
            `Status: ${ctx.status}`,
            `Header: ${JSON.stringify(ctx.header)}`,
            `ResponseLength: ${ctx.response.length}`,
            `Reffer: ${referer || 'null'}`,
            `UserAgent: ${userAgent || 'null'}`,
            `Url: ${ctx.url}`
        );
    }
}

export default compose([logger]);
